package com.caoji.user.web;

import com.caoji.advice.lyExcption;
import com.caoji.user.UserDto;
import com.caoji.user.entity.User;
import com.caoji.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
@RequestMapping("info")
public class UserController {
    @Autowired
    UserService userService;

    //根据用户名和密码查询
    @GetMapping
    public ResponseEntity<UserDto> Login(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ){
        return ResponseEntity.ok(userService.Login(username,password));
    }

    //注册
    @PostMapping
    public ResponseEntity<Void> resisty(
            @Valid User user, BindingResult result,
            @RequestParam("code") String code){
        if (result.hasErrors()) {
            String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new lyExcption(400, msg);
        }
        userService.resisty(user,code);
        return  ResponseEntity.status(HttpStatus.CREATED).build();
    }

    //判断信息是否存在
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> isexist(
            @PathVariable("data") String data,
            @PathVariable("type") Integer type
    ){
        return ResponseEntity.ok(userService.isexist(data,type));
    }

    //发送短信验证码
    @PostMapping("/code")
    public ResponseEntity<Void> sensms(
            @RequestParam("phone") String phone
    ){
        userService.sensms(phone);
        return  ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

}